package com.hmdp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    IUserService userService;

    @Override
    public Result follow(String userId, Boolean isFollow) {
        // 当前用户id
        Long currentUserId = UserHolder.getUser().getId();
        String key = "follows:" + currentUserId;
        // 查询当前用户是否已经关注了该用户
        Integer count = query().eq("follow_user_id", userId).eq("user_id", currentUserId).count();
        // 用户是要关注还是取关
        // 关注
        if (isFollow) {
            if (count == 0) {
                // 未关注，则新增关注记录
                Follow follow = new Follow().setFollowUserId(Long.parseLong(userId)).setUserId(currentUserId).setCreateTime(LocalDateTime.now());
                boolean save = save(follow);
                if (save){
                    // 保存关注id到redis  SADD userId followId
                    stringRedisTemplate.opsForSet().add(key, userId);
                }

            }
        }else {
            // 取关
            if (count > 0) {
                // 已关注，则删除关注记录
                boolean remove = remove(new QueryWrapper<Follow>().eq("follow_user_id", userId).eq("user_id", currentUserId));
                if (remove){
                    // 从redis中删除关注id  SREM userId followId
                    stringRedisTemplate.opsForSet().remove(key, userId);
                }
            }
        }
        return Result.ok();
    }

    @Override
    public Result isFollowed(Long userId) {
        // 当前用户id
        Long currentUserId = UserHolder.getUser().getId();
        // 查询当前用户是否已经关注了该用户
        Integer count = query().eq("follow_user_id", userId).eq("user_id", currentUserId).count();
        return Result.ok(count > 0);
    }

    @Override
    public Result commonFollowers(String userId) {
        // 分别查询该用户和当前用户的关注者列表
        Long currentUserId = UserHolder.getUser().getId();
        String meFollowersKey = "follows:" + currentUserId;
        String otherFollowersKey = "follows:" + userId;
        // 取交集
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(meFollowersKey, otherFollowersKey);
        List<Long> ids = intersect.stream().map(Long::parseLong).collect(Collectors.toList());
        if (ids == null || ids.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        // 获取共同关注者信息
        List<User> users = userService.listByIds(ids);
        return Result.ok(users);
    }
}
